package com.example.springboot_carlos.Controller;

import com.example.springboot_carlos.entiy.Article;
import com.example.springboot_carlos.entiy.User;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class useFull {
    static boolean isnull(Object obj){
        if(obj instanceof User) {
            User user = (User) obj;
            String str = user.toString();
            if (str.contains(null) || user.getUsername().isEmpty() || user.getPassword().isEmpty()
                    || user.getNickname().isEmpty() || user.getAge().isEmpty() || !user.getAge().matches("[0-9]+")) {
                return true;
            }
        }else if(obj instanceof Article){
            Article article = (Article) obj;
            String str = article.toString();
            if(str.contains(null)||article.getTitle().isEmpty()||article.getAuthor().isEmpty()||article.getContent().isEmpty()){
                return true;
            }
        }

        return false;
    }

    static String have_user(Connection connection, User user) throws SQLException {

        String sql="SELECT username,password " +
                "FROM userinfo " +
                "WHERE username=?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,user.getUsername());
        ResultSet rs=ps.executeQuery();
        if(rs.next()){
            return rs.getString("password");
        }
        return "No User";
    }

    static int intoDataBase(Connection connection, User user) throws SQLException {
        String sql = "INSERT INTO userinfo (username,password,nickname,age)" +
                "VALUES(?,?,?,?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,user.getUsername());
        ps.setString(2,user.getPassword());
        ps.setString(3,user.getNickname());
        ps.setInt(4,user.getIntAge());
        return ps.executeUpdate();
    }

    static int updateDataBasePassword(Connection connection, String username, String password) throws SQLException {
        String sql = "UPDATE userinfo " +
                "SET password=? " +
                "WHERE username=?";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,password);
        ps.setString(2,username);
        return ps.executeUpdate();
    }

    static int insertArticle(Connection connection,Article article) throws SQLException {
        String sql="INSERT INTO article (title,author,content) " +
                "VALUES(?,?,?)";
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1,article.getTitle());
        ps.setString(2,article.getAuthor());
        ps.setString(3,article.getContent());
        return ps.executeUpdate();
    }
}
